//
//  ViewController.swift
//  GameOfLife
//
//  Created by LLZ on 16/8/1.
//  Copyright © 2016年 ucsmy. All rights reserved.
//

import UIKit

let cellLength:CGFloat = 10.0
let density:Float = 0.2


class ViewController: UIViewController {

    @IBOutlet private weak var platform: UIView!
    @IBOutlet private weak var numLable: UILabel!
    
    @IBOutlet private weak var initBtn: UIButton!
    @IBOutlet private weak var nextBtn: UIButton!
    @IBOutlet private weak var runBtn: UIButton!
    
    private var cellNumX:Int = 0
    private var cellNumY:Int = 0
    private var gapX:CGFloat = 0.0
    private var gapY:CGFloat = 0.0
    private var cells:[Cell] = []
    private lazy var evolution = {
        return Evolution.defaultEvolution
    }()
    
    override  func viewDidLoad() {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.initializeCells(_:)), name: "Evolution_Initialize", object: nil)
       
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        cellNumX = Int(platform.rl_width / cellLength)
        cellNumY = Int(platform.rl_height / cellLength)
        gapX = (platform.rl_width % cellLength) / CGFloat(cellNumX - 1)
        gapY = (platform.rl_height % cellLength) / CGFloat(cellNumY - 1)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func initializeAction(sender: UIButton) {
        //移除所有cell
        for v in platform.subviews as [UIView] {
            v.removeFromSuperview()
        }
        cells.removeAll()
        evolution.initializeMap(cellNumX, cellNumY: cellNumY, density: density)
    }

    @IBAction func nextAction(sender: UIButton) {
        evolution.announceLocation()
    }
    
    @IBAction func runAction(sender: UIButton) {
        if sender.titleLabel?.text == "run" {
            evolution.run()
            sender.setTitle("stop", forState: .Normal)
        } else if sender.titleLabel?.text == "stop" {
            evolution.stop()
            sender.setTitle("run", forState: .Normal)
        }
    }
    
    
    @objc private func initializeCells(noti:NSNotification) {
        if let info = noti.userInfo {
            if let cell = info["cell"] as? Cell {
                let x = CGFloat(cell.x) * (cellLength + gapX)
                let y = CGFloat(cell.y) * (cellLength + gapY)
                cell.cellView.frame = CGRectMake(x, y, cellLength, cellLength)
                self.platform.addSubview(cell.cellView)
                cells.append(cell)
            }
        }
    }
}

